package com.honey.mybatis.generator.mappper;

import java.util.List;

import com.honey.compilation.xml.XmlElement;
import com.honey.core.dbmapping.introspect.IntrospectSchemaColumn;
import com.honey.core.dbmapping.introspect.IntrospectTableColumn;
import com.honey.core.dbmapping.structure.Schema;
import com.honey.core.dbmapping.structure.Table;
import com.honey.core.dbmapping.structure.TableColumn;
import com.honey.mybatis.generator.MybatisPlugin;
import com.honey.mybatis.generator.dao.DaoConstant;

public class UpdateByDynamic extends AbstractMybatisMapper{

	public UpdateByDynamic(MybatisPlugin belongPlugin) {
		super(belongPlugin);
	}

	public void appendElement(XmlElement parent, Schema schema, IntrospectSchemaColumn introspectSchemaColumn ){
		IntrospectTableColumn introspectTableColumn = null;
		if( schema instanceof Table ){
			introspectTableColumn = (IntrospectTableColumn)introspectSchemaColumn;
		}else{
			return ;
		}
		parent.addNewLine();
		parent.addComments(
				"更新记录集,主键和大字段不被更新(如果最后一列是主键这里生成的sql有错误)"
		);
		XmlElement update = new XmlElement(parent,"update")
		.addAttribute("id",MapperConstant.UPDATE_BY_DYNAMIC_MAPPER_ID)
		.addAttribute("parameterType","map")
		.addAttribute("timeout", mybatisPlugin.getConnectionTimeOut())
		.addTextElement("UPDATE " + schema.getName() +" SET ")
		;
		List<TableColumn> columns = introspectTableColumn.baseColumns();
		String modelPackage = super.getModelPrimitiveClassType(schema).getLongName();
		StringBuilder sb =new StringBuilder();
		for(int i=0,size =columns.size();i < size ; i++  ){
			TableColumn column = columns.get(i); 
			if(column.isPrimaryKey()) continue;
			sb.setLength(0);
			String fieldName =super.getFieldName(column);
			String typeHandler="";
			if( column.getEnumSchema() != null){
				typeHandler=",typeHandler=" + modelPackage ;
			}
			sb.append(column.getName()+" = #{"+DaoConstant.MAPPER_RECORD+"."+fieldName+",jdbcType="+JdbcTypeName.getJdbcTypeName(column.getJdbcType())+typeHandler+"}");
			if( i+1 < size ){
				sb.append(',');
			}
			update.addTextElement(sb.toString());
		}
		addUpdateDynamicCondition(update,introspectSchemaColumn.allColumns());
	}
}
